//
//  IPhoneAlarmAppDelegate.m
//  IPhoneAlarm
//
//  Created by Jeffrey Palm on 5/28/09.
//  Copyright Jeffrey Palm 2009. All rights reserved.
//

#import "IPhoneAlarmAppDelegate.h"
#import "IPhoneAlarmViewController.h"
#import <AudioToolbox/AudioToolbox.h>

#define kAccelerometerFrequency		10.0 // Hz
#define kFilteringFactor					  0.1
#define kThreshHold									0.1
#define kUnsetCoord							-9999

@interface IPhoneAlarmAppDelegate (PrivateMethods)
- (void)alarm;
- (void)startAlarm:(id)param;
@end


@implementation IPhoneAlarmAppDelegate

@synthesize window;
@synthesize viewController;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    
  // Override point for customization after app launch    
  [window addSubview:viewController.view];
  [window makeKeyAndVisible];
	
	//Configure and start accelerometer
	UIAccelerometer *acc = [UIAccelerometer sharedAccelerometer];
	[acc setUpdateInterval:(1.0 / kAccelerometerFrequency)];
	[acc setDelegate:self];

	// Note that we haven't yet set the original coordinate values
	coordsUnset = TRUE;
	
	// For testing, when not on the device just set off the alarm
#if TARGET_IPHONE_SIMULATOR
	[self alarm];
#endif
}

- (void)accelerometer:(UIAccelerometer*)accelerometer didAccelerate:(UIAcceleration*)acceleration {
	if (alarmOn) {
		return;
	}
	double x = acceleration.x;
	double y = acceleration.y;
	double z = acceleration.z;
	NSLog(@"%f\t%f\t%f", x, y, z);
	if (coordsUnset) {
		originalX		= x;
		originalY		= y;
		originalZ		= z;
		coordsUnset = FALSE;
		return;
	}
	double dx = originalX-x;
	double dy = originalY-y;
	double dz = originalZ-z;
	NSLog(@"\t\t%f\t%f\t%f", dx, dy, dz);
	if (dx >  kThreshHold || dy >  kThreshHold || dz >  kThreshHold ||
			dx < -kThreshHold || dy < -kThreshHold || dz < -kThreshHold) {
		[self alarm];
	}
}

- (void)alarm {
	alarmOn = TRUE;
	NSLog(@"alarm");
	[NSThread detachNewThreadSelector:@selector(startAlarm:) toTarget:self withObject:nil];	
	[viewController alarm];
}

- (void)startAlarm:(id)param {
	NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
	while (TRUE) {
		AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
		[NSThread sleepForTimeInterval:kAlarmSleep];
	}
	[autoreleasepool release];
}

- (void)acceleratedInX:(float)xx Y:(float)yy Z:(float)zz {
	printf("x2=%.2f y2=%.2f z2=%.2f\n", xx, yy, zz);
}


- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}


@end
